package com.my_spring.my_spring.controller;

import com.my_spring.my_spring.pojo.ResponseMessage;
import com.my_spring.my_spring.pojo.User;
import com.my_spring.my_spring.pojo.dto.UserDTO;
import com.my_spring.my_spring.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.annotation.RequestScope;

@RestController // 接口方法返回对象  转换成 json 文本
@RequestMapping("/user")  // localhost:8080/user
public class UserController {
    @Autowired  // 自动装配 bean
    IUserService userService;

    //  增加
    @PostMapping  //  会将统一类型转换成json文本 - 会调用getter方法 所以 ResponseMessage 需要 getter 和 setter
    public ResponseMessage<User> add(@Validated @RequestBody UserDTO user) { // 将传过来的文本自动转成对象
        //  新的user
      User userNew = userService.add(user);
    return ResponseMessage.success(userNew);
    }
    //  查询
    @GetMapping("/{userId}")
    public ResponseMessage find(@PathVariable Integer userId) {
        User userNew = userService.getUser(userId);
        return ResponseMessage.success(userNew);
    }
    //  修改
    @PutMapping
    public ResponseMessage edit(@Validated @RequestBody UserDTO user)  {
        User userNew = userService.edit(user);
        return ResponseMessage.success(userNew);
    }
    //  删除
    @DeleteMapping("/{userId}")
    public ResponseMessage delete(@PathVariable Integer userId) {
        userService.delete(userId);
        return ResponseMessage.success();
    }
}
